﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Windows;
using BrightIdeasSoftware;

namespace Genesis
{
    public partial class frmmain : Form
    {
        #region Variables
        // Playlist Variables
        TreeNode node;
        bool SelectMode = false;
        int currentPlaylist = 0;

        // Playback Control
        int PlayState = 0;
        int RepeatState = 0;
        int CurrentSongIndex = -1;
        int LastSongIndex = -1;
        bool Shuffled = false;

        // GUI
        Color PlayColor = Color.Brown;

        // Song Lists
        List<Song> ShuffleList = new List<Song>();

        #endregion
        #region Fuctions
        // Setting Functions
        private void UpdateSettings()
        {
            tVolume.Value = Internal_Settings.Volume;
            //Shuffle = Internal_Settings.Shuffle;
            RepeatState = Internal_Settings.RepeatState;

            if (RepeatState == 0)
                offToolStripMenuItem_Click(null, null);
            else if (RepeatState == 1)
                oneToolStripMenuItem_Click(null, null);
            else if (RepeatState == 2)
                allToolStripMenuItem_Click(null, null);


            olvMain.ForeColor = Visual_Settings.ForeColor;
            olvMain.BackColor = Visual_Settings.BackColor;
            olvMain.AlternateRowBackColor = Visual_Settings.AltBackColor;
            olvMain.RebuildColumns();

            olvName.Width = Visual_Settings.NameWidth;
            olvArtist.Width = Visual_Settings.ArtistWidth;
            olvAlbum.Width = Visual_Settings.AlbumWidth;
            olvGenre.Width = Visual_Settings.GenreWidth;
            olvTime.Width = Visual_Settings.TimeWidth;
            olvPlayCount.Width = Visual_Settings.PlayWidth;

        }
        private bool Valid_Library(string path)
        {
            try
            {
                string[] lines = File.ReadAllLines(path);
                if (lines[1].Contains("http://www.apple.com/DTDs/PropertyLis") == true)
                    return true;
                else
                    return false;
            }
            catch { return false; }

        }

        // Math Functions
        private string Time(int sec)
        {
            string min;
            string second;

            second = Convert.ToString(sec % 60);
            min = Convert.ToString(RoundDown(sec / 60));

            if (second.Length != 2)
                second = "0" + second;

            return min + ":" + second;
        }
        private double RoundDown(double valueToRound)
        {
            double floorValue = Math.Floor(valueToRound);
            if ((valueToRound - floorValue) > .5)
            {
                return (floorValue + 1);
            }
            else
            {
                return (floorValue);
            }
        }
        private int SelectedNode()
        {
            // Return library node if anything bugs out (0)
            if (tPlaylist.SelectedNode != null)
            {
                try { return Convert.ToInt32(tPlaylist.SelectedNode.Name); }
                catch { return 0; }
            }
            else
                return 0;
        }

        // GUI Functions
        private Color OLVMainBackColor(int index)
        {
            if (index % 2 == 0)
                return olvMain.BackColor;
            else
                return olvMain.AlternateRowBackColorOrDefault;
        }
        #endregion
        #region Methods
        // Playback Methods
        public void Play(int index)
        {
            if (Shuffled)
            {
                try { Library.CurrentSong = ShuffleList[index]; CurrentSongIndex = index; }
                catch
                {
                    try { Library.CurrentSong = ShuffleList[0]; CurrentSongIndex = 0; }
                    catch { return; }
                }

                if (PlayState == 0)
                {
                    libBNet.Play(Library.CurrentSong.Location, false);
                    PlayState = 1;

                    playToolStripMenuItem.Text = "Pause";
                    imgPlay.Image = Genesis.Properties.Resources.Pause_Normal;
                    SetStatus(Library.CurrentSong.Artist + " - " + Library.CurrentSong.Title, 1);

                    tmrBar.Enabled = true;
                }
                else if (PlayState == 1)
                {
                    libBNet.Pause();
                    PlayState = 2;
                    imgPlay.Image = Genesis.Properties.Resources.Play_Normal;
                    playToolStripMenuItem.Text = "Play";
                    SetStatus("Pause", 0);

                    tmrBar.Enabled = true;
                }
                else
                {
                    libBNet.Resume();
                    PlayState = 1;
                    playToolStripMenuItem.Text = "Pause";
                    imgPlay.Image = Genesis.Properties.Resources.Pause_Normal;
                    SetStatus(Library.CurrentSong.Artist + " - " + Library.CurrentSong.Title, 1);

                    tmrBar.Enabled = true;
                }

            }
            else
            {
                try { Library.CurrentSong = Library.CurrentList[index]; CurrentSongIndex = index; }
                catch
                {
                    try { Library.CurrentSong = Library.CurrentList[0]; CurrentSongIndex = 0; }
                    catch { return; }
                }

                if (PlayState == 0)
                {
                    libBNet.Play(Library.CurrentSong.Location, false);
                    PlayState = 1;

                    playToolStripMenuItem.Text = "Pause";
                    imgPlay.Image = Genesis.Properties.Resources.Pause_Normal;
                    SetStatus(Library.CurrentSong.Artist + " - " + Library.CurrentSong.Title, 1);

                    tmrBar.Enabled = true;
                }
                else if (PlayState == 1)
                {
                    libBNet.Pause();
                    PlayState = 2;
                    imgPlay.Image = Genesis.Properties.Resources.Play_Normal;
                    playToolStripMenuItem.Text = "Play";
                    SetStatus("Pause", 0);

                    tmrBar.Enabled = true;
                }
                else
                {
                    libBNet.Resume();
                    PlayState = 1;
                    playToolStripMenuItem.Text = "Pause";
                    imgPlay.Image = Genesis.Properties.Resources.Pause_Normal;
                    SetStatus(Library.CurrentSong.Artist + " - " + Library.CurrentSong.Title, 1);

                    tmrBar.Enabled = true;
                }
            }
        }
        public void Play(int index, bool fromStart)
        {
            if (fromStart)
                PlayState = 0;
            Play(index);
        }
        public void Next()
        {
            // Shuffled Mirrors Non Shuffled, except it's upper boundary is the
            // shuffle count, not the object listview count.
            if (Shuffled)
            {
                if (ShuffleList.Count > 0)
                {
                    if ((CurrentSongIndex == -1) && (ShuffleList.Count > 1))
                    {
                        if (PlayState == 0)
                        {
                            CurrentSongIndex = 1;
                            PlayState = 0;
                            Play(CurrentSongIndex);
                        }
                        else
                        {
                            CurrentSongIndex++;
                            PlayState = 0;
                            Play(CurrentSongIndex);
                        }
                    }
                    else if (CurrentSongIndex < ShuffleList.Count - 1)
                    {
                        CurrentSongIndex++;
                        PlayState = 0;
                        Play(CurrentSongIndex);
                    }
                    else if (CurrentSongIndex == ShuffleList.Count - 1)
                    {
                            CurrentSongIndex = 0;
                            PlayState = 0;
                            Play(CurrentSongIndex);
                    }
                }
            }
            else
            {
                if (olvMain.Items.Count > 0)
                {
                    // Special Event: Nothing is selected.
                    if ((olvMain.SelectedIndex == -1) && (olvMain.Items.Count > 1))
                    {
                        // First Use
                        if (PlayState == 0)
                        {
                            CurrentSongIndex = 1;
                            PlayState = 0;
                            Play(CurrentSongIndex);
                        }
                        // Songs have been controled by menu / buttons, not list.
                        else
                        {
                            CurrentSongIndex++;
                            PlayState = 0;
                            Play(CurrentSongIndex);
                        }
                    }
                    // Make sure there is another song to play.
                    else if (CurrentSongIndex < olvMain.Items.Count - 1)
                    {
                        CurrentSongIndex++;
                        PlayState = 0;
                        Play(CurrentSongIndex);
                    }
                    // Special Event: Last Song
                    else if (CurrentSongIndex == olvMain.Items.Count - 1)
                    {
                        if (RepeatState == 2)
                        {
                            CurrentSongIndex = 0;
                            PlayState = 0;
                            Play(CurrentSongIndex);
                        }
                        else
                        {
                            SetStatus("Ready", 0);
                        }
                    }
                }
            }
        }
        public void Previous()
        {
            if (Shuffled)
            {
                if (ShuffleList.Count > 0)
                {
                    if (CurrentSongIndex < 1)
                    {
                        if ((int)libBNet.GetPosition > 2)
                            libBNet.Seek((double)0);
                        else
                        {
                            CurrentSongIndex = ShuffleList.Count - 1;
                            PlayState = 0;
                            Play(CurrentSongIndex);
                        }
                    }
                    else if (CurrentSongIndex >= 0)
                    {
                        if ((int)libBNet.GetPosition > 2)
                            libBNet.Seek((double)0);
                        else
                        {
                            CurrentSongIndex--;
                            PlayState = 0;
                            Play(CurrentSongIndex);
                        }
                    }
                }
            }
            else
            {
                if (olvMain.Items.Count > 0)
                {
                    if (CurrentSongIndex < 1)
                    {
                        if (RepeatState == 2)
                        {
                            CurrentSongIndex = olvMain.Items.Count - 1;
                            PlayState = 0;
                            Play(CurrentSongIndex);
                        }
                        libBNet.Seek((double)0);
                    }
                    else if (CurrentSongIndex >= 0)
                    {
                        if ((int)libBNet.GetPosition > 2)
                            libBNet.Seek((double)0);
                        else
                        {
                            CurrentSongIndex--;
                            PlayState = 0;
                            Play(CurrentSongIndex);
                        }
                    }
                }
            }
        }
        public void Shuffle(int index)
        {
            List<Song> newList = new List<Song>();
            List<Song> song = new List<Song>();

            for (int i = 0; i < Library.CurrentList.Count; i++)
                song.Add(Library.CurrentList[i]);

            bool[] isUsed = new bool[song.Count];
            bool allUsed = false;

            for (int i = 0; i < isUsed.Length; i++)
                isUsed[i] = false;

            Random random = new Random();
            int rnd;

            newList.Add(song[index]);
            isUsed[index] = true;

            while (allUsed == false)
            {
                rnd = random.Next(0, isUsed.Length);
                if (isUsed[rnd] == false)
                {
                    newList.Add(song[rnd]);
                    isUsed[rnd] = true;

                    foreach (bool b in isUsed)
                    {
                        allUsed = true;
                        if (b == false)
                        {
                            allUsed = false;
                            break;
                        }
                    }
                }
            }
            ShuffleList = newList;
        }

        // GUI Methods
        private void SetStatus(string status, int type)
        {
            if (type == 0)
                Stat.Text = status;
            else if (type == 1)
            {
                this.Text = "Genesis (Beta) | " + status;
                Stat.Text = "Playing " + status;
            }
        }
        private void RefreshPlaylistMenu()
        {
            if (Library.Playlists.Length > 1)
            {
                if (tPlaylist.Nodes.Count > 1)
                {
                    node.Nodes.Clear();
                    for (int i = 1; i < Library.Playlists.Length; i++)
                        node.Nodes.Add(Convert.ToString(Library.Playlists[i].ID), Library.Playlists[i].Name);
                }
                else
                {
                    node = tPlaylist.Nodes.Add("Playlists", "Playlists");
                    for (int i = 1; i < Library.Playlists.Length; i++)
                        node.Nodes.Add(Convert.ToString(Library.Playlists[i].ID), Library.Playlists[i].Name);
                }
            }
            else
            {
                if (node != null)
                {
                    if (node.Nodes.Count > 0)
                    {
                        tPlaylist.Nodes.RemoveByKey("Playlists");
                        node.Nodes.Clear();
                    }
                }
            }
        }
        private void Reset_Track()
        {
            double time = libBNet.GetPosition;
            double length = libBNet.GetLength;

            TrackBar.Value = (int)time;
            lblCurrent.Text = Time((int)time);
            lblRemaining.Text = Time((int)(length - time));
            TrackBar.Value = 0;
            tmrBar.Enabled = false;
        }
        #endregion

        public frmmain()
        {
            InitializeComponent();
        }
        private void frmmain_Load(object sender, EventArgs e)
        {
            // Prevent Duplicate Instances of Genesis
            if (Windows.App.ProccessCount("Genesis") > 1)
            {
                MessageBox.Show("Another instance of Genesis is already running.", "Genesis", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                Application.Exit();
            }

            Settings.Load(Application.StartupPath);
            Library.LibraryPath = Application.StartupPath + @"\Library";
            libBNet.Initialize();
            Library.Load();

            olvMain.SetObjects(Library.Playlists[0].SongList);
            RefreshPlaylistMenu();
            
            SetStatus("Ready",0);
        }
        private void frmmain_Resize(object sender, EventArgs e)
        {
            olvMain.Height = this.Height - menuStrip.Height - 138;
            olvMain.Width = this.Width - tPlaylist.Width - 46;

            tPlaylist.Height = this.Height - menuStrip.Height - 138;
            PanelTrack.Width = this.Width - PanelTrack.Left - lblRemaining.Width - 8;

            TrackBar.Width = PanelTrack.Width - lblRemaining.Width - 27;
            lblRemaining.Left = TrackBar.Left + TrackBar.Width + 2;
        }
        private void frmmain_FormClosing(object sender, EventArgs e)
        {
            Library.Save();

            Internal_Settings.Volume = tVolume.Value;
            //Internal_Settings.Shuffle = Shuffle;
            Internal_Settings.RepeatState = RepeatState;

            Visual_Settings.NameWidth = olvName.Width;
            Visual_Settings.ArtistWidth = olvArtist.Width;
            Visual_Settings.AlbumWidth = olvAlbum.Width;
            Visual_Settings.GenreWidth = olvGenre.Width;
            Visual_Settings.TimeWidth = olvTime.Width;
            Visual_Settings.PlayWidth = olvPlayCount.Width;

            Settings.Save(Application.StartupPath);
        }

        // Buttons
        private void imgPlay_Click(object sender, EventArgs e)
        {
            Play(CurrentSongIndex);
        }
        private void imgPlay_MouseDown(object sender, MouseEventArgs e)
        {
            if (PlayState == 0)
                imgPlay.Image = Genesis.Properties.Resources.Play_Down;
            else if (PlayState == 1)
                imgPlay.Image = Genesis.Properties.Resources.Pause_Down;
            else if (PlayState == 2)
                imgPlay.Image = Genesis.Properties.Resources.Play_Down;
        }
        private void imgPlay_MouseUp(object sender, MouseEventArgs e)
        {
            if (PlayState == 0)
                imgPlay.Image = Genesis.Properties.Resources.Play_Normal;
            else if (PlayState == 1)
                imgPlay.Image = Genesis.Properties.Resources.Pause_Normal;
            else if (PlayState == 2)
                imgPlay.Image = Genesis.Properties.Resources.Play_Normal;
        }
        private void imgPlay_MouseLeave(object sender, EventArgs e)
        {
            if (PlayState == 0)
                imgPlay.Image = Genesis.Properties.Resources.Play_Normal;
            else if (PlayState == 1)
                imgPlay.Image = Genesis.Properties.Resources.Pause_Normal;
            else if (PlayState == 2)
                imgPlay.Image = Genesis.Properties.Resources.Play_Normal;
        }

        private void imgSkipN_Click(object sender, EventArgs e)
        {
            Next();
        }
        private void imgSkipN_MouseDown(object sender, MouseEventArgs e)
        {
            imgSkipN.Image = Genesis.Properties.Resources.SkipNext_Down;
        }
        private void imgSkipN_MouseUp(object sender, MouseEventArgs e)
        {
            imgSkipN.Image = Genesis.Properties.Resources.SkipNext_Normal;
        }

        private void imgSkipB_Click(object sender, EventArgs e)
        {
            Previous();
        }
        private void imgSkipB_MouseDown(object sender, MouseEventArgs e)
        {
            imgSkipB.Image = Genesis.Properties.Resources.SkipBack_Down;
        }
        private void imgSkipB_MouseUp(object sender, MouseEventArgs e)
        {
            imgSkipB.Image = Genesis.Properties.Resources.SkipBack_Normal;
        }

        // Library Control
        private void addSongToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FileDiag.Filter = "Supported Files|*.mp3;*.wav;*.ogg|mp3 Files|*.mp3|wav Files|*.wav|ogg Files|*.ogg";
            FileDiag.ShowDialog();
            if (FileDiag.FileName != "")
            {
                if (File.Exists(FileDiag.FileName))
                {
                    Library.AddSong(FileDiag.FileName);
                    olvMain.SetObjects(Library.Playlists[SelectedNode()].SongList);
                }
                else
                    MessageBox.Show("Invalid File", "Genesis", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void addFolderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (frmdirectory frmdir = new frmdirectory())
            {
                if (frmdir.ShowDialog(this) == DialogResult.OK)
                {
                    olvMain.SetObjects(Library.Playlists[SelectedNode()].SongList);
                }
            }
        }
        private void importITunesLibraryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (frmimport frmimp = new frmimport())
            {
                if (frmimp.ShowDialog(this) == DialogResult.OK)
                {
                    olvMain.SetObjects(Library.Playlists[SelectedNode()].SongList);
                }
            }
        }
        private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Library.RemoveSong((Song)olvMain.GetItem(olvMain.SelectedIndex).RowObject);
            olvMain.RemoveObject((Song)olvMain.GetItem(olvMain.SelectedIndex).RowObject);
        }

        private void editTitleToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (frmEdit frmedit = new frmEdit())
            {
                frmedit.Text = "Edit Title";
                Library.CurrentSong = (Song)olvMain.GetItem(olvMain.SelectedIndex).RowObject;
                if (frmedit.ShowDialog(this) == DialogResult.OK)
                {
                    olvMain.SetObjects(Library.Playlists[SelectedNode()].SongList);
                }
            }
        }
        private void editArtistToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (frmEdit frmedit = new frmEdit())
            {
                frmedit.Text = "Edit Artist";
                Library.CurrentSong = (Song)olvMain.GetItem(olvMain.SelectedIndex).RowObject;
                if (frmedit.ShowDialog(this) == DialogResult.OK)
                {
                    olvMain.SetObjects(Library.Playlists[SelectedNode()].SongList);
                }
            }
        }
        private void editAlbumToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (frmEdit frmedit = new frmEdit())
            {
                frmedit.Text = "Edit Album";
                Library.CurrentSong = (Song)olvMain.GetItem(olvMain.SelectedIndex).RowObject;
                if (frmedit.ShowDialog(this) == DialogResult.OK)
                {
                    olvMain.SetObjects(Library.Playlists[SelectedNode()].SongList);
                }
            }
        }
        private void editGenreToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (frmEdit frmedit = new frmEdit())
            {
                frmedit.Text = "Edit Genre";
                Library.CurrentSong = (Song)olvMain.GetItem(olvMain.SelectedIndex).RowObject;
                if (frmedit.ShowDialog(this) == DialogResult.OK)
                {
                    olvMain.SetObjects(Library.Playlists[SelectedNode()].SongList);
                }
            }
        }

        // iTunes Control
        private void iTunesLibraryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FileDiag.ShowDialog();
            Internal_Settings.iTunesLibraryPath = FileDiag.FileName;

            while (Valid_Library(Internal_Settings.iTunesLibraryPath) == false)
            {
                this.Focus();
                MessageBox.Show("'" + Internal_Settings.iTunesLibraryPath + "' is not a valid library. Please select a valid library.");
                FileDiag.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyMusic);
                FileDiag.ShowDialog();
                Internal_Settings.iTunesLibraryPath = FileDiag.FileName;
            }
            Visual_Settings.Save(Application.StartupPath + @"\Configuration\Config.gsf");
        }
        private void offToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            Windows.App.Kill("iTunes");
            Windows.Service.StopService("Apple Moblie Service", 5000);
            Windows.Service.StopService("Bonjour", 5000);
            Windows.Service.StopService("iPod Service", 5000);
        }
        private void onToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Windows.Service.StartService("Apple Moblie Service", 5000);
            Windows.Service.StartService("Bonjour", 5000);
            Windows.Service.StartService("iPod Service", 5000);
        }

        // OLV Control
        private void olvMain_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                e.Handled = true;
                e.SuppressKeyPress = true;

                Library.RemoveSong((Song)olvMain.GetItem(olvMain.SelectedIndex).RowObject);
                olvMain.RemoveObject((Song)olvMain.GetItem(olvMain.SelectedIndex).RowObject);
            }
            else if (e.KeyCode == Keys.Enter)
            {
                e.Handled = true;
                e.SuppressKeyPress = true;

                // Complile new list (based off of view)
                if (olvMain.Items.Count > 0)
                {
                    Library.CurrentList = new List<Song>();
                    for (int i = 0; i < olvMain.Items.Count; i++)
                        Library.CurrentList.Add((Song)olvMain.GetItem(i).RowObject);
                }

                if (olvMain.SelectedIndex != -1)
                {
                    if (Shuffled)
                    {
                        Shuffle(olvMain.SelectedIndex);
                        Shuffled = true;
                        shuffleToolStripMenuItem.Checked = true;
                        Play(0, true);
                    }
                    else
                        Play(olvMain.SelectedIndex, true);
                }
            }
            else if (e.KeyCode == Keys.Space)
            {
                e.Handled = true;
                e.SuppressKeyPress = true;

                Play(CurrentSongIndex);
            }
            else if (e.KeyCode == Keys.Right)
            {
                e.Handled = true;
                e.SuppressKeyPress = true;

                Next();
            }
            else if (e.KeyCode == Keys.Left)
            {
                e.Handled = true;
                e.SuppressKeyPress = true;

                Previous();
            }
        }
        private void olvMain_DoubleClick(object sender, EventArgs e)
        {
            if (olvMain.SelectedIndex != -1)
            {
                // Complile new list (based off of view)
                if (olvMain.Items.Count > 0)
                {
                    Library.CurrentList = new List<Song>();
                    for (int i = 0; i < olvMain.Items.Count; i++)
                        Library.CurrentList.Add((Song)olvMain.GetItem(i).RowObject);
                }

                if (Shuffled)
                {
                    Shuffle(olvMain.SelectedIndex);
                    Shuffled = true;
                    shuffleToolStripMenuItem.Checked = true;
                    Play(0, true);
                }
                else
                    Play(olvMain.SelectedIndex, true);
            }
        }
        private void olvMain_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (olvMain.SelectedIndex != -1)
            {
                Library.CurrentSong = (Song)olvMain.GetItem(olvMain.SelectedIndex).RowObject;
                olvMain.Items[2].BackColor = OLVMainBackColor(2);
            }
        }

        // Playback Control
        private void playToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Play(CurrentSongIndex);
        }
        private void nextToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Next();
        }
        private void previousToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Previous();
        }

        private void shuffleToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (Shuffled)
            {
                Shuffled = false;
                shuffleToolStripMenuItem.Checked = false;
            }
            else
            {
                if (olvMain.SelectedIndex != -1)
                {
                    Shuffle(olvMain.SelectedIndex);
                    Shuffled = true;
                    Play(0, true);
                }
                else
                    if (olvMain.Items.Count > 1)
                    {
                        CurrentSongIndex = 0;
                        Shuffle(CurrentSongIndex);
                        Shuffled = true;
                        Play(0, true);
                    }

                Shuffled = true;
                shuffleToolStripMenuItem.Checked = true;
            }
        }

        private void offToolStripMenuItem_Click(object sender, EventArgs e)
        {
            RepeatState = 0;
            offToolStripMenuItem.Checked = true;
            oneToolStripMenuItem.Checked = false;
            allToolStripMenuItem.Checked = false;
        }
        private void oneToolStripMenuItem_Click(object sender, EventArgs e)
        {
            RepeatState = 1;
            offToolStripMenuItem.Checked = false;
            oneToolStripMenuItem.Checked = true;
            allToolStripMenuItem.Checked = false;
        }
        private void allToolStripMenuItem_Click(object sender, EventArgs e)
        {
            RepeatState = 2;
            offToolStripMenuItem.Checked = false;
            oneToolStripMenuItem.Checked = false;
            allToolStripMenuItem.Checked = true;
        }

        // Playlist Control
        private void addToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (frmPlaylist frmpl = new frmPlaylist())
            {
                if (frmpl.ShowDialog(this) == DialogResult.OK)
                {
                    RefreshPlaylistMenu();
                }
            }
        }
        private void renameToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (SelectedNode() > 0)
            {
                Library.RenamePlaylistID = SelectedNode();
                Library.RenamePlaylist = true;
                using (frmPlaylist frmpl = new frmPlaylist())
                {
                    if (frmpl.ShowDialog(this) == DialogResult.OK)
                    {
                        RefreshPlaylistMenu();
                        Library.RenamePlaylist = false;
                    }
                }
            }
        }
        private void deletePlaylistToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (SelectedNode() > 0)
            {
                if (MessageBox.Show("Are you sure you would like to remove: " + Library.Playlists[SelectedNode()].Name + "?",
                    "Confirm Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    Library.RemovePlaylist(SelectedNode());
                    RefreshPlaylistMenu();
                }
            }
        }
        private void SelectSongToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (SelectMode)
            {
                foreach (int i in olvMain.CheckedIndices)
                    Library.Playlists[currentPlaylist].SongList.Add((Song)olvMain.GetItem(i).RowObject);

                olvMain.SetObjects(Library.Playlists[currentPlaylist].SongList);
                SelectMode = false;
                olvMain.CheckBoxes = false;
                SelectSongToolStripMenuItem.Text = "Select Song(s)";
                tPlaylist.SelectedNode = node.Nodes[node.Nodes.IndexOfKey(Convert.ToString(currentPlaylist))];
            }
            else
            {
                if (SelectedNode() > 0)
                {
                    currentPlaylist = SelectedNode();
                    olvMain.SetObjects(Library.Playlists[0].SongList);
                    SelectMode = true;
                    olvMain.CheckBoxes = true;
                    SelectSongToolStripMenuItem.Text = "Add Song(s)";
                    tPlaylist.SelectedNode = tPlaylist.Nodes[0];
                }
            }
        }

        private void tPlaylist_AfterSelect(object sender, TreeViewEventArgs e)
        {
            olvMain.SetObjects(Library.Playlists[SelectedNode()].SongList);
        }
        private void tPlaylist_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Delete)
            {
                e.Handled = true;
                deletePlaylistToolStripMenuItem_Click(null, null);
            }
        }

        // Timers & Tracks
        private void tmrBar_Tick(object sender, EventArgs e)
        {
            if (lblRemaining.Text != "0:00")
                TrackBar.Enabled = true;
            else
                TrackBar.Enabled = false;

                double time = libBNet.GetPosition;
                double length = libBNet.GetLength;

                TrackBar.Maximum = (int)length;
                TrackBar.Value = (int)time;
                lblCurrent.Text = Time((int)time);
                lblRemaining.Text = Time((int)(length - time));

                if ((time >= length) && ((length > 0)))
                {
                    Library.CurrentSong.PlayCount++;
                    olvMain.RefreshObject(olvMain.SelectedObject);

                    if (RepeatState == 1)
                    {
                        Reset_Track();
                        TrackBar.Maximum = (int)time;
                        Play(CurrentSongIndex, true);
                    }
                    else
                    {
                        Next();
                    }
                }
        }
        private void TrackBar_Scroll(object sender, EventArgs e)
        {
            double time = libBNet.GetPosition;
            double length = libBNet.GetLength;

            libBNet.Seek((double)TrackBar.Value);

            lblCurrent.Text = Time(TrackBar.Value);
            lblRemaining.Text = Time(TrackBar.Maximum - TrackBar.Value);
            this.Update();
        }
        private void TrackVolume_Scroll(object sender, EventArgs e)
        {
            libBNet.Volume(tVolume.Value);
        }

        // Visual Control
        private void gridLinesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (olvMain.GridLines == false)
            {
                olvMain.GridLines = true;
                gridLinesToolStripMenuItem.Checked = true;
            }
            else
            {
                olvMain.GridLines = false;
                gridLinesToolStripMenuItem.Checked = false;
            }
        }
        private void showGroupsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (olvMain.ShowGroups == true)
            {
                olvMain.ShowGroups = false;
                showGroupsToolStripMenuItem.Checked = false;
            }
            else
            {
                olvMain.ShowGroups = true;
                showGroupsToolStripMenuItem.Checked = true;
                olvMain.Sort();
            }
        }
        private void visualSettingsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (frmSettings settingswindow = new frmSettings())
            {
                if (settingswindow.ShowDialog(this) == DialogResult.OK)
                {
                    Settings.Save(Application.StartupPath);
                    UpdateSettings();
                }
            }
        }
    }
}
